<?php
/**
 * Created by PhpStorm.
 * User: work
 * Date: 18-6-23
 * Time: 下午4:48
 */

namespace PddWechat\Library;


use Dai\Framework\Base\BaseException;
use Dai\Framework\Library\ConfigLibrary;
use Dai\Framework\Library\HttpProxy;
use Dai\Framework\Library\Log;
use Dai\Framework\Library\RedisExt;
use PddWechat\Models\User\Data\UserData;
use PddWechat\Models\User\DataObject\UserDo;
use PddWechat\Models\User\Dto\WechatUserBasicInfo;
use PddWechat\Models\User\Dto\WechatUserOpenIdInfo;

class WechatLibrary
{
    public static function getAuthRedirectLoginUrl($uri, $state){
        $wechatConfig = ConfigLibrary::get("wechat", "basic");
        $authUrl =  ConfigLibrary::get("wechat" , "url", "authUrl");
        $redirectUrl = ConfigLibrary::get("wechat" , "url", "redirctUrl");
        $redirectUrl = sprintf($redirectUrl, urlencode($uri));
        $authRedirectUrl = sprintf($authUrl, $wechatConfig->appId, urlencode($redirectUrl), $state);
        return $authRedirectUrl;
    }

    /**
     * @param $code
     * @return WechatUserOpenIdInfo
     * @throws BaseException
     */
    public static function getWechatOpenIdInfo($code){
        $wechatConfig = ConfigLibrary::get("wechat", "basic");
        $getOpenIdUlr = ConfigLibrary::get("wechat" , "url", "getOpenIdUlr");
        $url = sprintf($getOpenIdUlr, $wechatConfig->appId, $wechatConfig->secret, $code);
        $res = HttpProxy::call($url);
        //$res = '{"access_token":"11_qxIawO4_BTRefrIANMeEBLG39jaXUFGr9TNeeri5rxOnDiTNKAU2rz0P0fIySaraOO0VeRn-NVzpqsCynEzIVlEx7Qsc2hCWyttGga_ukus","expires_in":7200,"refresh_token":"11_nAjZkaFWhGOkEkEcQzu8lUjY8hfqU4fQfJsyeOm_Yf0zkMntq4tLqvTAxwN82H-io2fJLsXvG0w2xAIB8KFKA93qLDyshafIFAgMPPo73ac","openid":"ofulZ02VkshM8a5Jm-4fFIg9H5QA","scope":"snsapi_userinfo"}';//HttpProxy::call($url);
        Log::info(sprintf("url is %s, response is %s", $url, $res));
	    $res = json_decode($res);
        if( isset($res->errcode) && $res->errcode > 0){
//            $wechatUserOpenIdInfo = new WechatUserOpenIdInfo();
//            $wechatUserOpenIdInfo->access_token = "11112";
//            $wechatUserOpenIdInfo->openid = 14;
//            return $wechatUserOpenIdInfo;
             throw new BaseException(BaseException::INTER_ERROR);
        }
        /** @var WechatUserOpenIdInfo $data */
        $data = $res;
        return $data;
    }

    /**
     * @param $openId
     * @return WechatUserBasicInfo
     * @throws BaseException
     */
    public static function getBasicUserInfo($openId, $token){
        $getBasicInfoUlr =  ConfigLibrary::get("wechat" , "url", "getBasicInfoUlr");
        $url = sprintf($getBasicInfoUlr, $token, $openId);
        $res = HttpProxy::call($url);
        Log::info(sprintf("url is %s, response is %s", $url, $res));
        $res = json_decode($res);
        if(isset($res->errcode) && $res->errcode != 0 ){
//            $wechatUserBasicInfo = new WechatUserBasicInfo();
//            $wechatUserBasicInfo->sex = 1;
//            $wechatUserBasicInfo->city = "1";
//            $wechatUserBasicInfo->headimgurl = "html";
//            $wechatUserBasicInfo->province ="b";
//            $wechatUserBasicInfo->nickname = "xxx";
//            return $wechatUserBasicInfo;
             throw new BaseException(BaseException::INTER_ERROR);
        }
        /** @var WechatUserBasicInfo $res */
        $res->openId = $openId;
        return self::getObjFromData($res);
    }


    /**
     * @param WechatUserBasicInfo $request
     * @return WechatUserBasicInfo
     */
    public static function getObjFromData($request) {
        $result = new WechatUserBasicInfo();
        $result->openId = $request->openId;
        $result->sex = $request->sex;
        $result->nickname = $request->nickname;
        $result->province = $request->province;
        $result->headimgurl = $request->headimgurl;
        $result->city= $request->city;
        return $result;
    }


    /**
     * @param $openId
     * @return mixed|string|WechatUserBasicInfo
     * @throws BaseException
     */
    public static function getBasicSubscribeUserInfo($openId){
        $getBasicInfoUlr =  ConfigLibrary::get("wechat" , "url", "getSubscribeUserUrl");
        $url = sprintf($getBasicInfoUlr, self::getWechatToken(), $openId);
        $res = HttpProxy::call($url);
        Log::info(sprintf("url is %s, response is %s", $url, $res));
        $res = json_decode($res);
        if(isset($res->errcode) && $res->errcode != 0 ){
            throw new BaseException(BaseException::INTER_ERROR);
        }
        /** @var WechatUserBasicInfo $res */
        $res->openId = $openId;
        return self::getObjFromData($res);
    }


    /**
     * 判断是否关注
     * @param $openId
     * @return mixed
     * @throws BaseException
     */
    public static function getSubscribe($openId){
        $getBasicInfoUlr =  ConfigLibrary::get("wechat" , "url", "getSubscribeUrl");
        $url = sprintf($getBasicInfoUlr, self::getWechatToken(), $openId);
        $res = HttpProxy::call($url);
        Log::info(sprintf("url is %s, response is %s", $url, $res));
        $res = json_decode($res);
        if(isset($res->errcode) && $res->errcode != 0 ){
            throw new BaseException(BaseException::INTER_ERROR);
        }
        return $res->subscribe;
    }

    public static function getWechatToken(){
        return RedisExt::getInstance()->get("gzh_access_token");
       // return "12_REWqaptKglDq3VuDwypSzynxhzLKPRBB5wA4nR8ihOkoZG9QWxLKo7PdfRAgh59FTdWfKWo0TkWq1-jNq3nZLaXaA7MUTAHsKCuQXSuFYw7eCNzNASwyNv5bDCiB8LprGd38vi4TwmdWIQ1IDSCgACAJYI";
    }

    public static function getWechatJsToken(){
        return RedisExt::getInstance()->get("gzh_js_tikcet");
    }

    public static function sendTemplate($userId, $openId, $data){
        $sendTemplateUrl =  ConfigLibrary::get("wechat" , "url", "sendTemplate");
        $url = sprintf($sendTemplateUrl, self::getWechatToken());
        $res = HttpProxy::call($url, $data);
        Log::info(sprintf("url is %s, data is %s, response is %s", $url, json_encode($data, JSON_UNESCAPED_UNICODE), $res));
        $res = json_decode($res);
        if(isset($res->errcode) && $res->errcode != 0 ){
            Log::info("sendTemplate $openId fatal\n");
            //没有关注, 更改状态
            if( $res->errcode == 43004) {
                $userData = new UserData();
                $userDo = new UserDo();
                $userDo->id = $userId;
                $userDo->subscribe = 0;
                $userData->edit($userDo);
            }
        }else {
            Log::info("send template to $openId success");
        }
    }

    public static function sendCustomer($userId, $openId, $data){
        $sendTemplateUrl =  ConfigLibrary::get("wechat" , "url", "sendCustomer");
        $url = sprintf($sendTemplateUrl, self::getWechatToken());
        $res = HttpProxy::call($url, $data);
        Log::info(sprintf("url is %s, data is %s, response is %s", $url, json_encode($data, JSON_UNESCAPED_UNICODE), $res));
        $res = json_decode($res);
        if(isset($res->errcode) && $res->errcode != 0 ){
            Log::info("sendCustomer $openId fatal\n");
            return false;
        }else {
            $userData = new UserData();
            $userDo = new UserDo();
            $userDo->id = $userId;
            $userDo->subscribe = 1;
            $userData->edit($userDo);
            Log::info("send sendCustomer to $openId success");
            return true;
        }
    }

    //获取回复文本消息
    public static function getReplyText($openId,$content)
    {
        $wechatConfig = ConfigLibrary::get("wechat", "basic");
        $replyXml = "<xml>
              <ToUserName><![CDATA[%s]]></ToUserName>
              <FromUserName><![CDATA[%s]]></FromUserName>
              <CreateTime>%s</CreateTime>
              <MsgType><![CDATA[text]]></MsgType>
              <Content><![CDATA[%s]]></Content>
            </xml>";
        return sprintf($replyXml, $openId, $wechatConfig->account, time(),$content);
    }

    //获取回复图片消息
    public static function getReplyImage($openId,$mediaId)
    {
        $wechatConfig = ConfigLibrary::get("wechat", "basic");
        $replyXml = "<xml>
              <ToUserName><![CDATA[%s]]></ToUserName>
              <FromUserName><![CDATA[%s]]></FromUserName>
              <CreateTime>%s</CreateTime>
              <MsgType><![CDATA[image]]></MsgType>
              <Image>
                <MediaId><![CDATA[%s]]></MediaId>
              </Image>
            </xml>";
        return sprintf($replyXml,$openId, $wechatConfig->account,time(),$mediaId);
    }

    //获取回复图文消息
    public static function getReplyNews($openId,$newsArr)
    {
        //判断是否为数组类型
        if(!is_array($newsArr) || empty($newsArr))
        {
            return;
        }

        $itemStr = "";
        //定义item模板
        $itemXml = "<item>
              <Title><![CDATA[%s]]></Title> 
              <Description><![CDATA[%s]]></Description>
              <PicUrl><![CDATA[%s]]></PicUrl>
              <Url><![CDATA[%s]]></Url>
            </item>";
        foreach($newsArr as $item) {
            $itemStr .= sprintf($itemXml,$item['Title'],$item['Description'],$item['PicUrl'],$item['Url']);
        }

        $wechatConfig = ConfigLibrary::get("wechat", "basic");
        return  "<xml>
              <ToUserName><![CDATA[".$openId."]]></ToUserName>
              <FromUserName><![CDATA[".$wechatConfig->account."]]></FromUserName>
              <CreateTime>".time()."</CreateTime>
              <MsgType><![CDATA[news]]></MsgType>
              <ArticleCount>".count($newsArr)."</ArticleCount>
              <Articles>".$itemStr."</Articles>
            </xml>";
    }

    public static function getQrCodeTicket($openId) {

        $url = "https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token=". self::getWechatToken();
        $data = '{"expire_seconds": 2592000, "action_name": "QR_STR_SCENE", "action_info": {"scene": {"scene_str": "'.$openId.'"}}}';

        $res = HttpProxy::call($url, $data);
        Log::info(sprintf("url is %s, data is %s, response is %s", $url, json_encode($data, JSON_UNESCAPED_UNICODE), $res));
        $res = json_decode($res);
        if(isset($res->errcode) && $res->errcode != 0 ){
            Log::info("sendCustomer  fatal\n");
            throw new BaseException( BaseException::INTER_ERROR);
        }else {
            Log::info("send sendCustomer to  success");
        }
        return $res->ticket;
    }

    public static function getQrCodeImage($ticket){
        return "https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=".$ticket;
    }

    public static function sendGetMediaId($fileName, $fileType){
        $access_token=self::getWechatToken();
        $data = array (
            "media" => new \CURLFile($fileName),
        );
        $url = "https://api.weixin.qq.com/cgi-bin/material/add_material?access_token=".$access_token."&type=".$fileType;
        $res = HttpProxy::call($url, $data);
        Log::info(sprintf("url is %s, data is %s, response is %s", $url, json_encode($data, JSON_UNESCAPED_UNICODE), $res));
        $res = json_decode($res);
        if(isset($res->errcode) && $res->errcode != 0 ){
            Log::info("sendCustomer  fatal\n");
            throw new BaseException( BaseException::INTER_ERROR);
        }else {
            Log::info("send sendCustomer to  success");
        }
        return $res;
    }
}
